<script setup lang='ts'>
import type { PlusColumn } from 'plus-pro-components'
import type { VxePagerEvents } from 'vxe-table'

import { useGetBuyerPage, useGetEnterprisePageAll, useGetEnterpriseSourceType, useGetEnterpriseType, useGetStockPage, useGetSupplierCategoryTree } from '@fl/api/man-api'
import { useGetByPage, useGetMallEnterpriseSourceType, useGetMallEnterpriseType, useGetSupplierStockCatList, useGetSupplierStockLabel } from '@fl/api/purchase'
import { SearchForm, SearchTable } from '@fl/components'
import { ElTree } from 'element-plus'
import { cloneDeep } from 'lodash-es'
import { useRouter } from 'vue-router'

import type { Tree } from './constant'

import { formTypeEnum, tableTypeEnum } from './constant'
import EditForm from './edit-form.vue'
import EditFormMall from './edit-form-mall.vue'
import TableForm from './table-form.vue'

const { push } = useRouter()

const { meta: { isAdmin } } = useRoute()

const editFormDom = computed(() => isAdmin ? EditForm : EditFormMall)

const enterpriseType = ref(2)

const tabEnum = {
    0: 'platform',
    1: 'enterprise',
    2: 'blacklist',
} as const

const tabsList = [
    {
        label: '平台供应商资源',
        name: tabEnum[0],
    },
    {
        label: '企业供应商库',
        name: tabEnum[1],
    },
    {
        label: '黑名单',
        name: tabEnum[2],
    },
]

const secondActiveName = ref<any>(tabEnum[0])

const { data: enterpriseTypeList, isLoading: enterpriseTypeLoading } = isAdmin ? useGetEnterpriseType(enterpriseType) : useGetMallEnterpriseType()
const { data: enterpriseSourceList, isLoading: enterpriseSourceLoading } = isAdmin ? useGetEnterpriseSourceType() : useGetMallEnterpriseSourceType()
const { data: serviceCategoryOptions, isLoading: serviceCategoryLoading } = useGetSupplierCategoryTree(isAdmin)

const stockCatPrams = computed(() => {
    return {
        isAdmin: !isAdmin,
        status: secondActiveName.value === tabEnum[1] ? 0 : secondActiveName.value === tabEnum[2] ? 2 : '',
    }
})

const { data: stockCatOptions, isLoading: stockCatLoading } = useGetSupplierStockCatList(stockCatPrams)

const loading = computed(() => enterpriseTypeLoading.value || enterpriseSourceLoading.value || serviceCategoryLoading.value || stockCatLoading.value)
console.log('🚀 ~ loading:', loading)

const enterpriseTypeOptions = computed(() => (enterpriseTypeList.value ?? []).map(x => ({ label: x.label, value: x.value })))
const enterpriseSourceListOptions = computed(() => (enterpriseSourceList.value ?? []).map(x => ({ label: x.label, value: x.value })))

const editVisible = ref<boolean>(false)
const tableVisible = ref<boolean>(false)

const id = ref<string | undefined>(undefined)

const formType = ref<any>()

const tableType = ref<any>()

const form = ref()

watchEffect(() => {
    if (!isAdmin) {
        tabsList.shift()
        secondActiveName.value = tabEnum[1]
    }
})

const columns: PlusColumn[] = [
    {
        label: '公司名称',
        prop: 'name',
    },
    {
        label: '供应商来源',
        options: enterpriseSourceListOptions,
        prop: 'source',
        valueType: 'select',
    },
    {
        label: '供应商类型',
        options: enterpriseTypeOptions,
        prop: 'secondType',
        valueType: 'select',
    },
    {
        colProps: {
            span: 12,
        },
        fieldProps: {
            type: 'datetimerange',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
        },
        hideInForm: !isAdmin,
        label: '时间范围',
        prop: 'time',
        valueType: 'date-picker',
    },
]

const initialState = {
    name: '',
    secondType: '',
    source: '',
    time: '',
}

const state = ref<any>(cloneDeep(initialState))

const gridOptions = computed(() => {
    return {
        columns: [
            { title: '序号', type: 'seq', width: 50 },
            { field: secondActiveName.value === tabEnum[0] ? 'enterpriseName' : 'supplierName', title: '公司名称' },
            { field: 'typeName', title: '企业类型' },
            { field: 'sourceName', title: '来源' },
            { field: 'catName', title: '服务类别', visible: secondActiveName.value !== tabEnum[0] },
            { field: 'supplierCategory', title: '供应商类别' },
            { field: 'contactName', title: '联系人' },
            { field: 'updateTime', title: '更新时间' },
            { slots: { default: 'operate' }, title: '操作', width: 350 },
        ],
        rowConfig: {
            keyField: 'id',
        },
        toolbarConfig: {
            slots: {
                buttons: 'toolbar_buttons',
            },
        },
    }
})

const initialPage = {
    currentPage: 1,
    pageSize: 10,
    total: 0,
}

const tablePage = ref(cloneDeep(initialPage))

const catId = ref('')

const catName = ref('')

const buyerId = ref('')

const filterText = ref('')

const searchParams = computed(() => {
    if (isAdmin) {
        return {
            buyerId: buyerId.value,
            catId: catId.value,
            page: tablePage.value.currentPage,
            size: tablePage.value.pageSize,
            stockStatus: secondActiveName.value === tabEnum[1] ? '1' : '2',
            type: 1,
            catType: 1,
            ...state.value,
            endTime: state.value?.time?.[1] ?? '',
            startTime: state.value?.time?.[0] ?? '',
            time: '',
        }
    }
    return {
        catId: catId.value,
        page: tablePage.value.currentPage,
        size: tablePage.value.pageSize,
        stockStatus: secondActiveName.value === tabEnum[1] ? '1' : '2',
        type: 1,
        catType: 1,
        ...state.value,
        time: '',
    }
})

const { data: tableDataAll, isLoading: tableAllLoading } = useGetEnterprisePageAll(searchParams, secondActiveName)

const { data: tableDataStock, isLoading: tableStockLoading } = isAdmin ? useGetStockPage(searchParams, secondActiveName) : useGetByPage(searchParams, secondActiveName)

const buyerParams = computed(() => {
    if (isAdmin) {
        return {
            name: filterText.value,
            page: 1,
            size: 99999,
        }
    }
    return {
        supplierName: filterText.value,
    }
})

const { data: buyerDate } = isAdmin ? useGetBuyerPage(buyerParams) : useGetSupplierStockLabel()

const tableLoading = computed(() => tableAllLoading.value || tableStockLoading.value)

const dataList = computed(() => {
    if (secondActiveName.value === tabEnum[0]) {
        return tableDataAll.value || []
    }
    return tableDataStock.value || []
})

const treeList = computed(() => {
    if (secondActiveName.value === tabEnum[0]) {
        return serviceCategoryOptions.value || []
    }
    return isAdmin
        ? (buyerDate.value?.records?.map((item: any) => ({ label: item.enterpriseName, value: item.id })) || [])
        : stockCatOptions.value
})

const buyerList = computed(() => {
    return isAdmin
        ? (buyerDate.value?.records?.map((item: any) => ({ label: item.enterpriseName, value: item.id })) || [])
        : (buyerDate.value?.map((item: any) => ({ label: item.supplierName, value: item.supplierId })) || [])
})

const treeRef = ref<InstanceType<typeof ElTree> | null>(null)

const defaultProps = {
    children: 'children',
    label: 'label',
}

watch(filterText, (val) => {
    treeRef.value!.filter(val)
})

function filterNode(value: string, data: Tree) {
    if (!value)
        return true
    return data.label.includes(value)
}

function reset() {
    tablePage.value = cloneDeep(initialPage)
    state.value = cloneDeep(initialState)
    catId.value = ''
    catName.value = ''
    filterText.value = ''
}

function submit(val: any) {
    tablePage.value.currentPage = 1
    state.value = cloneDeep(val)
}

const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.value.currentPage = currentPage
    tablePage.value.pageSize = pageSize
}

const wareHouseName = ref('')
const supplierCategory = ref('')

function wareHouse(row: any) {
    wareHouseName.value = row.enterpriseName
    supplierCategory.value = row.supplierCategory
    id.value = row.id
    showForm(formTypeEnum.warehouse)
}

function addAareHouse() {
    showForm(formTypeEnum.warehouse)
}

function remove(row: any) {
    wareHouseName.value = row.supplierName
    id.value = row.supplierId
    showForm(formTypeEnum.remove)
}

function addToBlackList(row: any) {
    wareHouseName.value = row.supplierName
    id.value = row.supplierId
    showForm(formTypeEnum.addtoblacklist)
}

function removeFromBlackList(row: any) {
    wareHouseName.value = row.supplierName
    id.value = row.supplierId
    showForm(formTypeEnum.removefromblacklist)
}

function showForm(val: string) {
    formType.value = val
    editVisible.value = true
}

function showInAndOut() {
    if (!buyerId.value && isAdmin) {
        return ElMessage.warning('请先选择采购商')
    }
    showTable(tableTypeEnum.inAndOut)
}

function showBlackList() {
    if (!buyerId.value && isAdmin) {
        return ElMessage.warning('请先选择采购商')
    }
    showTable(tableTypeEnum.blackList)
}

function showTable(val: string) {
    tableType.value = val
    tableVisible.value = true
}

// 编辑查看
function doEdit(row: any, type = 'edit') {
    push({
        path: '/operations-pages/operations-enterprise-management/supplier-database-edit',
        query: {
            id: row.id,
            secondType: row.secondType,
            sourceName: row.sourceName,
            supplierId: row?.supplierId || row.id, // test id '1807243484231385090'
            supplierName: row?.supplierName || row.enterpriseName,
            type,
            typeName: row.typeName,
        },
    })
}
function handleNodeClick(data: Tree) {
    if (secondActiveName.value === tabEnum[0] || !isAdmin) {
        catId.value = data.value
        catName.value = data.label
    }
    else {
        buyerId.value = data.value
    }
}
function handleClick(val: any) {
    form.value?.formInstance.handleReset()
    const activename = val.props.name
    buyerId.value = (activename === tabEnum[1] || activename === tabEnum[2]) ? buyerDate.value?.records?.[0]?.id : ''
    treeRef.value?.setCurrentKey(((activename === tabEnum[1] || activename === tabEnum[2]) && isAdmin) ? buyerDate.value?.records?.[0]?.id : '')
}

function goCheck(row: any) {
    push(
        {
            path: '/operations-pages/operations-enterprise-management/operations-enterprise-info-check',
            query: {
                id: row.id,
                name: secondActiveName.value === tabEnum[0] ? row.enterpriseName : row.supplierName,
                source: 'manufacturer',
                type: 1,
            },
        },
    )
}

watchEffect(() => {
    if (secondActiveName.value === tabEnum[0]) {
        tablePage.value.total = tableDataAll.value?.total ?? 0
    }
    else {
        tablePage.value.total = tableDataStock.value?.total ?? 0
    }
})

watchEffect(() => {
    if (stockCatOptions.value) {
        setTimeout(() => {
            treeRef.value?.setCurrentKey('')
            catId.value = ''
        }, 100)
    }
})
watchEffect(() => {
    if (serviceCategoryOptions.value && secondActiveName.value === tabEnum[0]) {
        setTimeout(() => {
            treeRef.value?.setCurrentKey('')
            catId.value = ''
        }, 100)
    }
})
watchEffect(() => {
    if (buyerDate.value && (secondActiveName.value === tabEnum[1] || secondActiveName.value === tabEnum[2])) {
        // console.log(buyerDate.value)
        setTimeout(() => {
            treeRef.value?.setCurrentKey(buyerDate.value?.records?.[0]?.id)
            buyerId.value = buyerDate.value?.records?.[0]?.id
        }, 100)
    }
})
</script>

<template>
    <el-container h-full>
        <el-header mb-10>
            <el-tabs v-model="secondActiveName"
                     type="border-card"
                     @tab-click="handleClick"
            >
                <el-tab-pane v-for="item in tabsList"
                             :key="item.name"
                             :label="item.label"
                             :name="item.name"
                />
            </el-tabs>
        </el-header>

        <el-container>
            <el-aside width="250px"
                      class="mr-10"
            >
                <el-input v-model="filterText"
                          placeholder="请输入关键字"
                />

                <ElTree ref="treeRef"
                        style="max-width: 600px;max-height:600px;overflow:auto"
                        class="filter-tree"
                        :data="treeList"
                        :props="defaultProps"
                        highlight-current
                        default-expand-all
                        :filter-node-method="filterNode"
                        :expand-on-click-node="false"
                        node-key="value"
                        @node-click="handleNodeClick"
                />
            </el-aside>

            <el-main>
                <SearchForm v-bind="state"
                            ref="form"
                            submit-text="搜索"
                            :columns="columns"
                            @reset="reset"
                            @submit="submit"
                />

                <SearchTable v-bind="gridOptions"
                             v-model:pager="tablePage"
                             :loading="tableLoading"
                             :data="dataList?.records"
                             @page-change="handlePageChange"
                >
                    <template v-if="secondActiveName !== tabEnum[0]"
                              #toolbar_buttons
                    >
                        <ElButton v-if="secondActiveName === tabEnum[1] && !isAdmin"
                                  type="primary"
                                  @click="addAareHouse"
                        >
                            新增入库
                        </ElButton>

                        <ElButton v-if="secondActiveName === tabEnum[1]"
                                  type="primary"
                                  @click="showInAndOut"
                        >
                            出入库记录
                        </ElButton>

                        <ElButton v-if="secondActiveName === tabEnum[2]"
                                  type="primary"
                                  @click="showBlackList"
                        >
                            黑名单记录
                        </ElButton>
                    </template>

                    <template #operate="{ row }">
                        <el-button v-if="isAdmin"
                                   text
                                   @click="doEdit(row, 'view')"
                        >
                            查看
                        </el-button>

                        <template v-if="secondActiveName === tabEnum[0]">
                            <el-button text
                                       @click="doEdit(row)"
                            >
                                编辑
                            </el-button>

                            <el-button text
                                       @click="wareHouse(row)"
                            >
                                入库
                            </el-button>

                            <el-button text
                                       @click="goCheck(row)"
                            >
                                查看经销商
                            </el-button>
                        </template>

                        <template v-if="secondActiveName === tabEnum[1]">
                            <el-button text
                                       @click="remove(row)"
                            >
                                移出
                            </el-button>

                            <el-button text
                                       @click="addToBlackList(row)"
                            >
                                加入黑名单
                            </el-button>
                        </template>

                        <template v-if="secondActiveName === tabEnum[2]">
                            <el-button text
                                       @click="removeFromBlackList(row)"
                            >
                                移出黑名单
                            </el-button>
                        </template>
                    </template>
                </SearchTable>
            </el-main>
        </el-container>
    </el-container>

    <component :is="editFormDom"
               :key="id"
               v-model:visible="editVisible"
               v-model:id="id"
               v-model:type="formType"
               v-model:wareHouseName="wareHouseName"
               v-model:supplierCategory="supplierCategory"
               v-model:buyerId="buyerId"
               v-model:buyerList="buyerList"
               v-model:catId="catId"
               v-model:catName="catName"
    />

    <TableForm :key="String(tableVisible)"
               v-model:visible="tableVisible"
               v-model:id="id"
               v-model:buyerId="buyerId"
               v-model:type="tableType"
    />
</template>

<style lang="scss" scoped>
.el-header {
    padding: 0;
    height: auto;
}

.el-main {
    padding: 10px;
}

:deep(.el-card__body) {
    height: 100%;
}

:deep(.el-tabs__content) {
    padding: 0;
}
</style>
